package com.timebank.volunteer.service.impl;

import com.timebank.common.core.constant.SecurityConstants;
import com.timebank.common.core.constant.VolunteerExceptionConstant;
import com.timebank.common.core.exception.volunteer.VolunteerException;
import com.timebank.common.core.result.Result;
import com.timebank.common.core.web.pojo.AjaxResult;
import com.timebank.common.security.utils.SecurityUtils;
import com.timebank.system.pojo.SysUser;
import com.timebank.system.service.RemoteUserService;
import com.timebank.timecoin.pojo.entity.TimeCoinTrade;
import com.timebank.timecoin.service.RemoteTimeCoinService;
import com.timebank.volunteer.mapper.VolunteerAttendListMapper;
import com.timebank.volunteer.mapper.VolunteerMapper;
import com.timebank.volunteer.pojo.entity.Volunteer;
import com.timebank.volunteer.pojo.entity.VolunteerAttendList;
import com.timebank.volunteer.pojo.vo.VolunteerAttendListVO;
import com.timebank.volunteer.service.VolunteerAttendListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 志愿服务 出席名单 实现类
 * @author shiliuyinzhen
 */
@Service
public class VolunteerAttendListServiceImpl implements VolunteerAttendListService {

    @Autowired
    private VolunteerMapper volunteerMapper;

    @Autowired
    private VolunteerAttendListMapper volunteerAttendListMapper;

    @Resource
    private RemoteTimeCoinService remoteTimeCoinService;

    @Resource
    private RemoteUserService remoteUserService;

    /**
     * 根据志愿服务Id获取出席名单
     * @param volunteerId 志愿服务Id
     * @return
     */
    @Override
    public List<VolunteerAttendListVO> getAttendListByVolunteerId(Long volunteerId) {
        VolunteerAttendList volunteerAttendList = VolunteerAttendList.builder()
                .volunteerId(volunteerId)
                .build();
        return volunteerAttendListMapper.getAttendList(volunteerAttendList);
    }

    /**
     * 校验用户权限
     * @param volunteerId 志愿服务Id
     * @return
     */
    private Volunteer checkUserPermission(Long volunteerId) {
        //查询志愿服务
        Volunteer volunteer = volunteerMapper.getVolunteerById(volunteerId);
        if (volunteer == null){
            throw new VolunteerException(VolunteerExceptionConstant.VOLUNTEER_NOT_FOUND +",id: " + volunteerId);
        }
        Long userId = SecurityUtils.getUserId();
        //如果该用户不是管理员，也不是志愿服务的发布人
        if (!SecurityUtils.isAdmin(userId) && volunteer.getPublisherId() != userId){
            //没有相关权限
            throw new VolunteerException(VolunteerExceptionConstant.USER_NOT_HAVE_PERMISSION);
        }
        return volunteer;
    }

    /**
     * 批量删除出席名单
     * @param volunteerId
     * @param userIds
     * @return
     */
    @Override
    public AjaxResult deleteAttendListByVolunteerIdAndUserIds(Long volunteerId, Long[] userIds) {
        //校验用户权限
        checkUserPermission(volunteerId);
        //批量删除时间币交易
        AjaxResult ajaxResult = remoteTimeCoinService.deleteTradeByUserIdsAndVolunteerId(userIds, volunteerId, SecurityConstants.INNER);
        if (ajaxResult.isError()){
            return AjaxResult.error("删除时间币交易失败");
        }
        return volunteerAttendListMapper.deleteAttendListByVolunteerIdAndUserIds(volunteerId,userIds) > 0 ? AjaxResult.success("删除成功") : AjaxResult.error("删除失败");
    }

    /**
     * 批量添加出席名单
     * @param volunteerId
     * @param userIds
     * @return
     */
    @Override
    @Transactional
    public AjaxResult batchInsertAttendList(Long volunteerId, Long[] userIds) {
        //校验用户权限
        Volunteer volunteer = checkUserPermission(volunteerId);
        List<VolunteerAttendList> volunteerAttendLists = new ArrayList<>();
        //查询用户信息
        Result<List<SysUser>> usersResult = remoteUserService.getUserByIds(List.of(userIds), SecurityConstants.INNER);
        List<SysUser> sysUsers = usersResult.getData();
        for (SysUser sysUser : sysUsers) {
            //查询出席列表中是否已经存在
            VolunteerAttendList volunteerAttendList = VolunteerAttendList.builder()
                    .volunteerId(volunteerId)
                    .userId(sysUser.getUserId())
                    .build();
            List<VolunteerAttendListVO> attendLists = volunteerAttendListMapper.getAttendList(volunteerAttendList);
            //如果出席名单不为空
            if (!attendLists.isEmpty()){
                return AjaxResult.error("用户id："+ sysUser.getUserId() + " 已经存在");
            }
            volunteerAttendList = VolunteerAttendList.builder()
                    .volunteerId(volunteerId)
                    .userId(sysUser.getUserId())
                    .createId(SecurityUtils.getUserId())
                    .createBy(SecurityUtils.getUsername())
                    .createTime(LocalDateTime.now())
                    .signTotalTime(2)
                    .remark("发布者手动添加")
                    .build();
            volunteerAttendLists.add(volunteerAttendList);
            //创建时间币交易
            TimeCoinTrade timeCoinTrade = TimeCoinTrade.builder()
                    .volunteerId(volunteerId)
                    .payerId(volunteer.getPublisherId())
                    .payerName(volunteer.getCreateBy())
                    .getterId(sysUser.getUserId())
                    .getterName(sysUser.getUserName())
                    .timeCoin(volunteer.getTimeCoin())
                    .build();
            timeCoinTrade.setCreateBy(SecurityUtils.getUsername());
            timeCoinTrade.setCreateTime(LocalDateTime.now());
            timeCoinTrade.setRemark("发布者手动添加出席名单，自动创建");
            AjaxResult ajaxResult = remoteTimeCoinService.createTrade(timeCoinTrade, SecurityConstants.INNER);
            if (ajaxResult.isError()){
                return AjaxResult.error("创建时间币交易失败");
            }
        }
        return volunteerAttendListMapper.batchInsertAttendList(volunteerAttendLists) > 0 ? AjaxResult.success("添加成功") : AjaxResult.error("添加失败");
    }
}
